//
//  ZNTabBar.m
//  ZNTabBarController
//
//  Created by Sniper on 15/12/23.
//  Copyright © 2015年 Sniper. All rights reserved.
//

#import "ZNTabBar.h"

@implementation ZNTabBar

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initZNTabBar];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initZNTabBar];
    }
    return self;
}

- (void)initZNTabBar {
    _backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tabbarBackground"]];
    _backgroundView.autoresizesSubviews = YES;
    _backgroundView.contentMode = UIViewContentModeScaleAspectFill;
//    _backgroundView.clipsToBounds = YES;
    [self addSubview:_backgroundView];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGRect frame = self.frame;
    _backgroundView.frame = CGRectMake(0, 2, self.bounds.size.width, self.bounds.size.height - 2);
    
    CGFloat itemWidth = frame.size.width / [self.itemsArray count];
    
    NSInteger index = 0;
    
    for (ZNTabBarItem *tabbarItem in self.itemsArray) {
        if ([self.itemsArray count] / 2 == index) {
            tabbarItem.isMiddleItem = YES;
        }
        tabbarItem.frame = CGRectMake(index * itemWidth, 0, itemWidth, frame.size.height);
        
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"tabbar%ld", (long)index]];
        UIImage *image_selected = [UIImage imageNamed:[NSString stringWithFormat:@"tabbar%ld_selected", (long)index]];
        [tabbarItem setSelectedItemImage:image_selected unselectedItemImage:image];
        [tabbarItem setNeedsDisplay];
        index += 1;
    }
}

- (void)setItemsArray:(NSArray *)itemsArray {
    for (ZNTabBarItem *item in _itemsArray) {
        [item removeFromSuperview];
    }
    
    _itemsArray = [itemsArray copy];
    for (ZNTabBarItem *item in _itemsArray) {
        [item addTarget:self action:@selector(tabBarItemWasSelected:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:item];
    }
}

- (void)tabBarItemWasSelected:(id)sender {
    
    [self setSelectedItem:sender];
    
    if ([self.delegate respondsToSelector:@selector(tabbar:didSelectItemAtIndex:)]) {
        NSInteger index = [self.itemsArray indexOfObject:_selectedItem];
        [self.delegate tabbar:self didSelectItemAtIndex:index];
    }
}

-(void)setSelectedItem:(ZNTabBarItem *)selectedItem {
    if (selectedItem == _selectedItem) {
        return;
    }
    [_selectedItem setSelected:NO];
    
    _selectedItem = selectedItem;
    [_selectedItem setSelected:YES];

}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
